package com.lvideo.component.extraplayer.videoview;

import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.MediaController;

import com.letv.sdk.callbacks.LetvPlayerView;
import com.lvideo.component.extraplayer.Interface.MyAdStatusListener;
import com.lvideo.component.extraplayer.LVideoMediaPlayerControl;
import com.lvideo.component.extraplayer.utils.MyPlayerConstant;
import com.lvideo.component.extraplayer.utils.SohuPlayerDefinition;
import com.media.ffmpeg.FFMpegPlayer;
import com.novaplayer.info.PlayUrl;
import com.novaplayer.listener.OnSubtitleListener;
import com.novaplayer.listener.OnVideoViewStateChangeListener;
import com.tencent.qqlive.mediaplayer.api.TVK_IMediaPlayer;
import com.tencent.qqlive.mediaplayer.api.TVK_IProxyFactory;
import com.tencent.qqlive.mediaplayer.api.TVK_NetVideoInfo;
import com.tencent.qqlive.mediaplayer.api.TVK_PlayerMsg;
import com.tencent.qqlive.mediaplayer.api.TVK_PlayerVideoInfo;
import com.tencent.qqlive.mediaplayer.api.TVK_SDKMgr;
import com.tencent.qqlive.mediaplayer.api.TVK_UserInfo;
import com.tencent.qqlive.mediaplayer.view.IVideoViewBase;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by biandi on 2016/12/21.
 */

public class VideoViewTencentProxy implements LVideoMediaPlayerControl {

    private Context mContext;
    private TVK_IProxyFactory factory;
    private IVideoViewBase videoView;
    private TVK_IMediaPlayer videoPlayer;
    private TVK_NetVideoInfo netVideoInfo;
    private int mCurrPlayTime = 0;

    private OnPreparedListener mOnPreparedListener;
    private OnCompletionListener mOnCompletionListener;
    private OnInfoListener mOnInfoListener;
    private MediaPlayer.OnErrorListener mOnErrorListener;
    private MediaPlayer.OnSeekCompleteListener mOnSeekCompleteListener;
    private MediaPlayer.OnVideoSizeChangedListener mOnVideoSizeChangedListener;
    private MediaPlayer.OnBufferingUpdateListener mOnBufferingUpdateListener;
    private OnVideoViewStateChangeListener mOnVideoViewStateChangeListener;
    private MyAdStatusListener mOnAdStatusListener;

    public static final String DEF_MSD = "msd"; // 流畅
    public static final String DEF_SD = "sd"; // 标清
    public static final String DEF_HD = "hd"; // 高清
    public static final String DEF_SHD = "shd"; // 超高清
    public static final int CHARGE_STATE_NO_PAY = -2;
    private int firstErrorCode = 0;

    public VideoViewTencentProxy(Context context) {
        this.mContext = context;
        factory = TVK_SDKMgr.getProxyFactory();
        videoView = factory.createVideoView(context);//surfaceview
        videoPlayer = factory.createMediaPlayer(context, videoView);
        initListener();
    }

    private void initListener() {
        videoPlayer.setOnAdClickedListener(new TVK_IMediaPlayer.OnAdClickedListener() {

            @Override
            public void onLandingViewClosed(TVK_IMediaPlayer mpImpl) {

            }

            @Override
            public void onAdWarnerTipClick(TVK_IMediaPlayer mpImpl) {

            }

            @Override
            public void onAdSkipClick(TVK_IMediaPlayer mpImpl, boolean isCopyRightForWarner) {

            }

            @Override
            public void onAdReturnClick(TVK_IMediaPlayer mpImpl) {
                if (mOnAdStatusListener != null) {
                    mOnAdStatusListener.onAdFinished();
                }
            }

            @Override
            public void onAdFullScreenClick(TVK_IMediaPlayer mpImpl) {
                if (mOnVideoSizeChangedListener != null) {
                    mOnVideoSizeChangedListener.onVideoSizeChanged(null,0,0);
                }
            }

            @Override
            public void onAdExitFullScreenClick(TVK_IMediaPlayer mpImpl) {
                if (mOnVideoSizeChangedListener != null) {
                    mOnVideoSizeChangedListener.onVideoSizeChanged(null,0,0);
                }
            }
        });

        videoPlayer.setOnVideoPreparedListener(new TVK_IMediaPlayer.OnVideoPreparedListener() {

            @Override
            public void onVideoPrepared(TVK_IMediaPlayer mpImpl) {
                ((Activity)mContext).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mOnPreparedListener != null) {
                            mOnPreparedListener.onPrepared(null);
                        }
                        if (mOnInfoListener != null) {
                            mOnInfoListener.onInfo(null, MyPlayerConstant.START_TO_PLAY, 0);
                        }
                    }
                });
                videoPlayer.start();
                videoPlayer.seekTo(mCurrPlayTime);
            }
        });
        videoPlayer.setOnCompletionListener(new TVK_IMediaPlayer.OnCompletionListener() {

            @Override
            public void onCompletion(TVK_IMediaPlayer mpImpl) {
                ((Activity)mContext).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mOnCompletionListener != null) {
                            mOnCompletionListener.onCompletion(null);
                        }
                    }
                });
            }
        });

        videoPlayer.setOnPreAdListener(new TVK_IMediaPlayer.OnPreAdListener() {

            @Override
            public void onPreAdPreparing(TVK_IMediaPlayer mpImpl) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onPreAdPrepared(TVK_IMediaPlayer mpImpl, long adDuration) {
                ((Activity)mContext).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mOnPreparedListener != null) {
                            mOnPreparedListener.onPrepared(null);
                        }
                    }
                });
            }
        });
        videoPlayer.setOnErrorListener(new TVK_IMediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(TVK_IMediaPlayer mpImpl, int model, int what, int extra, String detailInfo,
                                   Object Info) {
                final int tModel = model;
                final int tWhat = what;
                final int tExtra = extra;
                ((Activity)mContext).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mOnErrorListener != null) {
                            firstErrorCode = tModel;
                            mOnErrorListener.onError(null, tWhat, tExtra);
                        }
                    }
                });
                return false;
            }
        });
        videoPlayer.setOnInfoListener(new TVK_IMediaPlayer.OnInfoListener() {

            @Override
            public boolean onInfo(TVK_IMediaPlayer mpImpl, int what, Object extra) {

                switch (what) {
                    case TVK_PlayerMsg.PLAYER_INFO_START_BUFFERING:
                        //Toast.makeText(mContext, "视频开始缓冲", Toast.LENGTH_SHORT).show();
                        ((Activity)mContext).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (mOnInfoListener != null) {
                                    mOnInfoListener.onInfo(null, MediaPlayer.MEDIA_INFO_BUFFERING_START, 0);
                                }
                            }
                        });
                        break;
                    case TVK_PlayerMsg.PLAYER_INFO_ENDOF_BUFFERING:
                        //Toast.makeText(mContext, "视频缓冲结束", Toast.LENGTH_SHORT).show();
                        ((Activity)mContext).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (mOnInfoListener != null) {
                                    mOnInfoListener.onInfo(null, MediaPlayer.MEDIA_INFO_BUFFERING_END, 0);
                                }
                            }
                        });
                        break;
                    default:
                        break;
                }
                return false;
            }
        });
        videoPlayer.setOnNetVideoInfoListener(new TVK_IMediaPlayer.OnNetVideoInfoListener() {
            @Override
            public void onNetVideoInfo(TVK_IMediaPlayer tvk_iMediaPlayer, TVK_NetVideoInfo tvk_netVideoInfo) {
                netVideoInfo = tvk_netVideoInfo;
                if (tvk_netVideoInfo != null && tvk_netVideoInfo.getChargeState() == CHARGE_STATE_NO_PAY) {
                    ((Activity)mContext).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (mOnErrorListener != null) {
                                mOnErrorListener.onError(null, CHARGE_STATE_NO_PAY, 0);
                            }
                        }
                    });
                }
            }
        });
        videoPlayer.setOnVideoPreparingListener(new TVK_IMediaPlayer.OnVideoPreparingListener() {
            @Override
            public void onVideoPreparing(TVK_IMediaPlayer tvk_iMediaPlayer) {

            }
        });
    }

    @Override
    public void setVideoPlayUrl(PlayUrl url) {

    }

    @Override
    public void setVideoPath(String videoPath) {

    }

    @Override
    public void setVideoPath(String videoPath, Map<String, String> headers) {

    }

    @Override
    public void stopPlayback() {
        videoPlayer.stop();
        videoPlayer.release();
    }

    @Override
    public void forward() {

    }

    @Override
    public void rewind() {

    }

    @Override
    public void adjust(int type) {

    }

    @Override
    public MediaPlayer getMediaPlayer() {
        return null;
    }

    @Override
    public void setOnAdListener(MyAdStatusListener var) {
        mOnAdStatusListener = var;
    }

    @Override
    public View getView() {
        return (View) videoView;
    }

    @Override
    public int getLastSeekWhenDestoryed() {
        return 0;
    }

    @Override
    public boolean isPaused() {
        return videoPlayer.isPauseing();
    }

    @Override
    public boolean isInPlaybackState() {
        return false;
    }

    @Override
    public void setMediaController(MediaController controller) {

    }

    @Override
    public void setOnPreparedListener(OnPreparedListener l) {
        this.mOnPreparedListener = l;
    }

    @Override
    public void setOnCompletionListener(OnCompletionListener l) {
        this.mOnCompletionListener = l;
    }

    @Override
    public void setOnInfoListener(OnInfoListener l) {
        this.mOnInfoListener = l;
    }

    @Override
    public void setOnErrorListener(MediaPlayer.OnErrorListener l) {
        this.mOnErrorListener = l;
    }

    @Override
    public void setOnSeekCompleteListener(MediaPlayer.OnSeekCompleteListener l) {
        this.mOnSeekCompleteListener = l;
    }

    @Override
    public void setOnVideoSizeChangedListener(MediaPlayer.OnVideoSizeChangedListener l) {
        this.mOnVideoSizeChangedListener = l;
    }


    @Override
    public void setOnBufferingUpdateListener(MediaPlayer.OnBufferingUpdateListener l) {
        this.mOnBufferingUpdateListener = l;
    }

    @Override
    public void setVideoViewStateChangeListener(OnVideoViewStateChangeListener videoViewStateChangeListener) {
        this.mOnVideoViewStateChangeListener = videoViewStateChangeListener;
    }

    @Override
    public void setOnSubtitleListener(OnSubtitleListener onSubtitleListener) {

    }

    @Override
    public void setInitPosition(int i) {

    }

    @Override
    public void switchStreamSource(String s, int i, int i1) {

    }

    @Override
    public int setSourceType(int i) {
        return 0;
    }

    @Override
    public void setParameter(int i, Object o) {

    }

    @Override
    public boolean handleTouchEvent(MotionEvent motionEvent) {
        return false;
    }

    @Override
    public void usingSensor(int i, boolean b) {

    }

    @Override
    public void setLanguage(String s) {

    }

    @Override
    public String[] getLanguage() {
        return new String[0];
    }

    @Override
    public void setOnAdNumberListener(FFMpegPlayer.OnAdNumberListener l) {

    }

    @Override
    public void setOnBlockListener(FFMpegPlayer.OnBlockListener l) {

    }

    @Override
    public void setOnHardDecodeErrorListener(FFMpegPlayer.OnHardDecodeErrorListner l) {

    }

    @Override
    public boolean isEnforcementWait() {
        return false;
    }

    @Override
    public void setEnforcementWait(boolean enforcementWait) {

    }

    @Override
    public boolean isEnforcementPause() {
        return false;
    }

    @Override
    public void setEnforcementPause(boolean enforcementPause) {

    }

    @Override
    public void setCacheSize(int video_size, int audio_size, int picutureSize, int startpic_size) {

    }

    @Override
    public boolean isSohuAdvertInPlayback() {
        return videoPlayer.isPlayingAD();
    }

    @Override
    public void next() {

    }

    @Override
    public void playVideoAt(int index) {

    }

    @Override
    public List<Integer> getSupportDefinitions() {
        if (netVideoInfo == null) {
            return null;
        }
        ArrayList<TVK_NetVideoInfo.DefnInfo> defList = netVideoInfo.getDefinitionList();
        List<Integer> list = new ArrayList<Integer>();
        if (defList != null && defList.size() > 0) {
            for (TVK_NetVideoInfo.DefnInfo info : defList) {
                if (info != null) {
                    Integer defint = new Integer(getDefCode(info.getmDefn()));
                    list.add(defint);
                }
            }
        }
        return list;
    }

    @Override
    public void changeDefinition(int definition) {
        videoPlayer.switchDefinition(getDefString(definition));
    }

    @Override
    public int getCurrentDefinition() {
        String defn = "";
        if (netVideoInfo != null && netVideoInfo.getCurDefinition() != null) {
            defn = netVideoInfo.getCurDefinition().getmDefn();
        }
        return getDefCode(defn);
    }

    @Override
    public void start() {
        videoPlayer.start();
    }

    @Override
    public void pause() {
        videoPlayer.onClickPause();
    }

    @Override
    public int getDuration() {
        return (int) videoPlayer.getDuration();
    }

    @Override
    public int getCurrentPosition() {
        return (int) videoPlayer.getCurrentPostion();
    }

    @Override
    public void seekTo(int i) {
        videoPlayer.seekTo(i);
        mCurrPlayTime = i;
        if (mOnSeekCompleteListener != null) {
            mOnSeekCompleteListener.onSeekComplete(null);
        }
    }

    @Override
    public boolean isPlaying() {
        return videoPlayer.isPlaying();
    }

    @Override
    public int getBufferPercentage() {
        return 0;
    }

    @Override
    public boolean canPause() {
        return true;
    }

    @Override
    public boolean canSeekBackward() {
        return false;
    }

    @Override
    public boolean canSeekForward() {
        return false;
    }

    @Override
    public int getAudioSessionId() {
        return 0;
    }

    @Override
    public void setTencentData(TVK_UserInfo userinfo, TVK_PlayerVideoInfo playerinfo,int currPlayTime) {
        videoPlayer.stop();
        videoPlayer.openMediaPlayer(mContext, userinfo, playerinfo, "", 0, 0);
        mCurrPlayTime = currPlayTime;
    }

    @Override
    public void setLetvScreenView(LetvPlayerView letvScreenView) {

    }

    @Override
    public void setLetvData(long vid,int currPlayTime) {

    }

    @Override
    public void setBestvData(String vid, String fdnCode, long currPlayTime) {

    }

    @Override
    public int getFirstErrorCode() {
        return firstErrorCode;
    }

    private int getDefCode(String def) {
        if (TextUtils.isEmpty(def)) {
            return SohuPlayerDefinition.PE_DEFINITION_UNDEFINED;
        }
        if (def.equals(DEF_MSD)) {
            // 流畅
            return SohuPlayerDefinition.PE_DEFINITION_NOR;
        } else if (def.equals(DEF_SD)) {
            // 标清
            return SohuPlayerDefinition.PE_DEFINITION_HIGH;
        } else if (def.equals(DEF_HD)) {
            // 高清
            return SohuPlayerDefinition.PE_DEFINITION_SUPER;
        } else if (def.equals(DEF_SHD)) {
            // 超高清
            return SohuPlayerDefinition.PE_DEFINITION_ORIGINAL;
        }
        return SohuPlayerDefinition.PE_DEFINITION_UNDEFINED;
    }

    private String getDefString(int code) {
        String defStr = "";
        switch (code) {
            case SohuPlayerDefinition.PE_DEFINITION_NOR:
                defStr = DEF_MSD;
                break;
            case SohuPlayerDefinition.PE_DEFINITION_HIGH:
                defStr = DEF_SD;
                break;
            case SohuPlayerDefinition.PE_DEFINITION_SUPER:
                defStr = DEF_HD;
                break;
            case SohuPlayerDefinition.PE_DEFINITION_ORIGINAL:
                defStr = DEF_SHD;
                break;
        }
        return defStr;
    }

    @Override
    public void onDestroyData() {
        videoView = null;
        videoPlayer = null;
    }
}
